package fortunata.jspwikiplugins.vpoet;

import com.ecyrd.jspwiki.plugin.WikiPlugin;
import com.ecyrd.jspwiki.plugin.PluginException;
import com.ecyrd.jspwiki.WikiContext;

import org.apache.log4j.Logger;

import java.util.Map;
import fortunata.FortunataPlugin;
import fortunata.fswapps.vpoet.Vpoet;

/**
 * This plugin is invoked when an operation button is pressed in the "listing wiki page".
 */
public class OnListOperation extends FortunataPlugin implements WikiPlugin {
    private static Logger log = Logger.getLogger( OnListOperation.class );

    public String execute (WikiContext context, Map parameterMap) throws PluginException {
       String wikiTextMessage = "";
       try{
            //Reads a hidden field that holds the number of items in the list
            String strNumItems   = FormManager.getFieldValue("numItems",  parameterMap);
            int numItems = Integer.parseInt(strNumItems);
            int selectedItem = 0;
            String value = "";
            System.out.println("numItems = " + numItems);
            //Read the button name that was pressed
            if (parameterMap.get("doEdit") != null){
                //Search for an item Selected
                System.out.println("en doEdit");
                for (int i = 1; i <= numItems ; i++){
                    value = (String)parameterMap.get("item" + i);
                    System.out.println("getting item" + i);
                    if (value!= null){
                       selectedItem = i;
                       System.out.println("selected item = " + i);
                       break;
                    }
                }
                if (selectedItem != 0){
                    System.out.println("selectedItem = " +   selectedItem);
                    System.out.println("value = " +   value);
                   //context.getHttpRequest().getSession().setAttribute(Vpoet.sessionAttribute_EditElement, value);
                   //context.getWikiSession().addMessage(Vpoet.sessionTopic_FormWikiPageName, "val1");
                }else{  //None is selected
                     throw new PluginException(renderWikiText(context, "You have to selected one element"));
                }
                //Show results message
                wikiTextMessage = "%%information "+ nl +
                                  "Click here: [" + Vpoet.editWikiPageName + "]" + nl +
                                  "%%";
            }else {
                wikiTextMessage = "%%warning "+ nl +
                                  "Sorry. Operation not available now" + nl +
                                  "%%";
            }
            return renderWikiText(context, wikiTextMessage);
        } catch(PluginException e){
            //Shows a nice red alert with the message.
            throw new PluginException(renderWikiText(context, e.getMessage()));
        }

    }

}
